package com.zhangxun.listener;


import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.zhangxun.MessageObj;
import com.zhangxun.constant.QueueConstant;
import com.zhangxun.domain.MsgNoticeDto;
import com.zhangxun.domain.Order;
import com.zhangxun.feign.MessageOrderFeign;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
public class MessageListener {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Value("${message.template_id}")
    private String templateId;

    @Value("message.topcolor")
    private String topcolor;

    @Value("${message.url}")
    private String messageUrl;


    @Autowired
    private MessageOrderFeign messageOrderFeign;



    @RabbitListener(queues = QueueConstant.DEAD_MSG_QUEUE)
    public void messageNotice(Message message, Channel channel){
        String str = new String(message.getBody());
        MsgNoticeDto msgNoticeDto = JSON.parseObject(str, MsgNoticeDto.class);

        //根据订单号查询数据库订单状态
        String orderNumber = msgNoticeDto.getOrderNum();
       Order order = messageOrderFeign.loadById(orderNumber);
       //查看订单状态，如果订单是未支付，则发消息给用户提醒支付。
       if(order.getStatus() == 1){
           //封装传输的数据进对象，然后转换成json字符串
           MessageObj messageObj = new MessageObj();
           messageObj.setTouser(msgNoticeDto.getWxUserId());
           messageObj.setTemplate_id(templateId);
           messageObj.setTopcolor(topcolor);

           Map<String,String> orderNo = MessageObj.getMap();
           orderNo.put("value",orderNumber);
           orderNo.put("color",topcolor);

           Map<String, String> money = MessageObj.getMap();
           money.put("value",msgNoticeDto.getTotalPrice().toString());
           money.put("color",topcolor);
           Map<String,Map<String,String>> data = new HashMap<>();
           data.put("orderNo",orderNo);
           data.put("money",money);
           messageObj.setData(data);
           String msg = JSON.toJSONString(data);
           String url = String.format(messageUrl, stringRedisTemplate.opsForValue().get("access_token"));

           //发送消息推送
           HttpUtil.post(url, msg);


       }
       //签收消息
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
